/*
 * Copyright (c) 2020 HiHope Community.
 * Description: mq2 demo
 * Author: HiSpark Product Team.
 * Create: 2020-5-20
 */
#include <ultrasonic.h>
#include <hi_time.h>
#include <hi_adc.h>
#include <hi_uart.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include "MPU6050.h"
#include "wifiiot_errno.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_i2c.h"
#include "wifiiot_i2c_ex.h"

#include <math.h>
#include <hi_early_debug.h>
#include <hi_task.h>
#include <hi_time.h>
#include <hi_adc.h>
#include <hi_stdlib.h>
#include <hi_watchdog.h>
#include <hi_i2c.h>
#include <hi_io.h>
#include <hi_gpio.h>
#include <math.h>

#include <hi_time.h>
#include <hi_adc.h>
#include <hi_uart.h>

#define MPU_AD0_CTRL			PAout(15)	//控制AD0电平,从而控制MPU地址
#define MPU_SELF_TESTX_REG		0X0D	//自检寄存器X
#define MPU_SELF_TESTY_REG		0X0E	//自检寄存器Y
#define MPU_SELF_TESTZ_REG		0X0F	//自检寄存器Z
#define MPU_SELF_TESTA_REG		0X10	//自检寄存器A
#define MPU_SAMPLE_RATE_REG		0X19	//采样频率分频器
#define MPU_CFG_REG						0X1A	//配置寄存器
#define MPU_GYRO_CFG_REG			0X1B	//陀螺仪配置寄存器
#define MPU_ACCEL_CFG_REG			0X1C	//加速度计配置寄存器
#define MPU_MOTION_DET_REG		0X1F	//运动检测阀值设置寄存器
#define MPU_FIFO_EN_REG				0X23	//FIFO使能寄存器
#define MPU_I2CMST_CTRL_REG		0X24	//IIC主机控制寄存器
#define MPU_I2CSLV0_ADDR_REG	0X25	//IIC从机0器件地址寄存器
#define MPU_I2CSLV0_REG				0X26	//IIC从机0数据地址寄存器
#define MPU_I2CSLV0_CTRL_REG	0X27	//IIC从机0控制寄存器
#define MPU_I2CSLV1_ADDR_REG	0X28	//IIC从机1器件地址寄存器
#define MPU_I2CSLV1_REG				0X29	//IIC从机1数据地址寄存器
#define MPU_I2CSLV1_CTRL_REG	0X2A	//IIC从机1控制寄存器
#define MPU_I2CSLV2_ADDR_REG	0X2B	//IIC从机2器件地址寄存器
#define MPU_I2CSLV2_REG				0X2C	//IIC从机2数据地址寄存器
#define MPU_I2CSLV2_CTRL_REG	0X2D	//IIC从机2控制寄存器
#define MPU_I2CSLV3_ADDR_REG	0X2E	//IIC从机3器件地址寄存器
#define MPU_I2CSLV3_REG				0X2F	//IIC从机3数据地址寄存器
#define MPU_I2CSLV3_CTRL_REG	0X30	//IIC从机3控制寄存器
#define MPU_I2CSLV4_ADDR_REG	0X31	//IIC从机4器件地址寄存器
#define MPU_I2CSLV4_REG				0X32	//IIC从机4数据地址寄存器
#define MPU_I2CSLV4_DO_REG		0X33	//IIC从机4写数据寄存器
#define MPU_I2CSLV4_CTRL_REG	0X34	//IIC从机4控制寄存器
#define MPU_I2CSLV4_DI_REG		0X35	//IIC从机4读数据寄存器
#define MPU_I2CMST_STA_REG		0X36	//IIC主机状态寄存器
#define MPU_INTBP_CFG_REG			0X37	//中断/旁路设置寄存器
#define MPU_INT_EN_REG				0X38	//中断使能寄存器
#define MPU_INT_STA_REG				0X3A	//中断状态寄存器
#define MPU_ACCEL_XOUTH_REG		0X3B	//加速度值,X轴高8位寄存器
#define MPU_ACCEL_XOUTL_REG		0X3C	//加速度值,X轴低8位寄存器
#define MPU_ACCEL_YOUTH_REG		0X3D	//加速度值,Y轴高8位寄存器
#define MPU_ACCEL_YOUTL_REG		0X3E	//加速度值,Y轴低8位寄存器
#define MPU_ACCEL_ZOUTH_REG		0X3F	//加速度值,Z轴高8位寄存器
#define MPU_ACCEL_ZOUTL_REG		0X40	//加速度值,Z轴低8位寄存器
#define MPU_TEMP_OUTH_REG			0X41	//温度值高八位寄存器
#define MPU_TEMP_OUTL_REG			0X42	//温度值低8位寄存器
#define MPU_GYRO_XOUTH_REG		0X43	//陀螺仪值,X轴高8位寄存器
#define MPU_GYRO_XOUTL_REG		0X44	//陀螺仪值,X轴低8位寄存器
#define MPU_GYRO_YOUTH_REG		0X45	//陀螺仪值,Y轴高8位寄存器
#define MPU_GYRO_YOUTL_REG		0X46	//陀螺仪值,Y轴低8位寄存器
#define MPU_GYRO_ZOUTH_REG		0X47	//陀螺仪值,Z轴高8位寄存器
#define MPU_GYRO_ZOUTL_REG		0X48	//陀螺仪值,Z轴低8位寄存器
#define MPU_I2CSLV0_DO_REG		0X63	//IIC从机0数据寄存器
#define MPU_I2CSLV1_DO_REG		0X64	//IIC从机1数据寄存器
#define MPU_I2CSLV2_DO_REG		0X65	//IIC从机2数据寄存器
#define MPU_I2CSLV3_DO_REG		0X66	//IIC从机3数据寄存器
#define MPU_I2CMST_DELAY_REG	0X67	//IIC主机延时管理寄存器
#define MPU_SIGPATH_RST_REG		0X68	//信号通道复位寄存器
#define MPU_MDETECT_CTRL_REG	0X69	//运动检测控制寄存器
#define MPU_USER_CTRL_REG			0X6A	//用户控制寄存器
#define MPU_PWR_MGMT1_REG			0X6B	//电源管理寄存器1
#define MPU_PWR_MGMT2_REG			0X6C	//电源管理寄存器2 
#define MPU_FIFO_CNTH_REG			0X72	//FIFO计数寄存器高八位
#define MPU_FIFO_CNTL_REG			0X73	//FIFO计数寄存器低八位
#define MPU_FIFO_RW_REG				0X74	//FIFO读写寄存器
#define MPU_DEVICE_ID_REG			0X75	//器件ID寄存器
#define GY521_ADDR      0X68    //陀螺仪addr
#define	SMPLRT_DIV		0x19	//陀螺仪采样率，典型值：0x07(125Hz)
#define	CONFIG			0x1A	//低通滤波频率，典型值：0x06(5Hz)
#define	GYRO_CONFIG		0x1B	//陀螺仪自检及测量范围，典型值：0x18(不自检，2000deg/s)
#define	ACCEL_CONFIG	0x1C	//加速计自检、测量范围及高通滤波频率，典型值：0x01(不自检，2G，5Hz)
#define	ACCEL_XOUT_H	0x3B
#define	ACCEL_XOUT_L	0x3C
#define	ACCEL_YOUT_H	0x3D
#define	ACCEL_YOUT_L	0x3E
#define	ACCEL_ZOUT_H	0x3F
#define	ACCEL_ZOUT_L	0x40
#define	TEMP_OUT_H		0x41
#define	TEMP_OUT_L		0x42
#define	GYRO_XOUT_H		0x43
#define	GYRO_XOUT_L		0x44	
#define	GYRO_YOUT_H		0x45
#define	GYRO_YOUT_L		0x46
#define	GYRO_ZOUT_H		0x47
#define	GYRO_ZOUT_L		0x48
#define	PWR_MGMT_1		0x6B	//电源管理，典型值：0x00(正常启用)
#define	WHO_AM_I			0x75	//IIC的ADDR寄存器(默认数值0x68，只读)
#define	SlaveAddress	0xD0	//IIC写入时的ADDR字节数据，+1为读取

#define Kp 100.0f                        // 比例增益支配率收敛到加速度计/磁强计
#define Ki 0.002f                // 积分增益支配率的陀螺仪偏见的衔接
#define halfT 0.001f                // 采样周期的一半

#define MPU_ADDR_WRITE 0
#define MPU_ADDR_READ  1
#define MPU_SEND_DATA_BUFF 20
float q0 = 1, q1 = 0, q2 = 0, q3 = 0;          // 四元数的元素，代表估计方向
float exInt = 0, eyInt = 0, ezInt = 0;        // 按比例缩小积分误差

float Yaw = 0.0, Pitch = 0.0,Roll = 0.0; 
hi_u8 Gy521_Write_Byte(hi_u8 addr, hi_u8 data)
{
    hi_i2c_idx id = 0;
    hi_i2c_data i2c_data = {0};
    hi_u8 buf[3] = {addr,data};
    i2c_data.send_len = 2;
    i2c_data.send_buf = buf;
    hi_u32 ret = 0;
    ret = hi_i2c_write(id, GY521_ADDR<<1|MPU_ADDR_WRITE, &i2c_data);
    return ret;
}
hi_u8 Gy521_Write_Len(hi_u8 addr, hi_u8 reg, hi_u8 len, hi_u8 *buf)
{
    hi_i2c_idx id = 0;
    hi_i2c_data i2c_data = {0};
    hi_u32 ret = 0;
    hi_u8 data[MPU_SEND_DATA_BUFF] = {0};

    /* send reg*/
    data[0] = reg;
    /*send reg and data*/
    memcpy(&data[0]+1, buf, len);
    /*i2c send reg and data  config*/
    i2c_data.send_len = len +1;
    i2c_data.send_buf = data;
   
    ret = hi_i2c_write(id, addr<<1|MPU_ADDR_WRITE, &i2c_data);
    if (ret == HI_ERR_I2C_INVALID_PARAMETER) {
        printf("i2c invalid parameter 0x%x\r\n", ret);
        return HI_ERR_FAILURE;
    } 
    if (ret == HI_ERR_I2C_WAIT_SEM_FAIL) {
        printf("i2c wait sem failed 0x%x\r\n", ret);
        HI_ERR_FAILURE;
    }
    return ret;
}

hi_u8 GY521_Read_Len(hi_u8 addr, hi_u8 reg, hi_u8 len, hi_u8 *data)
{
    hi_i2c_idx id = 0;
    hi_u32 ret = 0;
    hi_i2c_data i2c_data = {0};
    hi_u8 tem[1] = {reg};

    /*send reg config*/
    i2c_data.send_len = 1;
    i2c_data.send_buf = tem;
    /*read data config*/
    i2c_data.receive_len = len;
    i2c_data.receive_buf = data;
    /*send reg*/
    ret = hi_i2c_write(id, addr<<1|MPU_ADDR_WRITE, &i2c_data);
    if (ret == HI_ERR_I2C_INVALID_PARAMETER) {
        printf("GY521_Read_Len : i2c invalid parameter 0x%x\r\n", ret);
        return HI_ERR_FAILURE;
    } 
    /*read data*/
    ret = hi_i2c_read(id, addr<<1|MPU_ADDR_READ, &i2c_data);
   
    if (ret == HI_ERR_I2C_WAIT_SEM_FAIL) {
        printf("i2c wait sem failed 0x%x\r\n", ret);
        return HI_ERR_I2C_WAIT_SEM_FAIL;
    } else if(ret == HI_ERR_I2C_NOT_INIT) {
        printf("i2c not init 0x%x\r\n", ret);
        return HI_ERR_I2C_NOT_INIT;
    }
	return HI_ERR_SUCCESS;

}
hi_void InitMPU6050(hi_void)
{
    hi_io_set_func(WIFI_IOT_IO_NAME_GPIO_13, WIFI_IOT_IO_FUNC_GPIO_13_I2C0_SDA);   
    hi_io_set_func(WIFI_IOT_IO_NAME_GPIO_14, WIFI_IOT_IO_FUNC_GPIO_14_I2C0_SCL);   
    hi_i2c_init(WIFI_IOT_I2C_IDX_0, 400000); /* baudrate: 400kbps */
    hi_i2c_set_baudrate(WIFI_IOT_I2C_IDX_0, 400000);
     Gy521_Write_Byte(PWR_MGMT_1,0X80); 
hi_sleep(100);
    Gy521_Write_Byte(PWR_MGMT_1, 0x00);	//解除休眠状态
	Gy521_Write_Byte(SMPLRT_DIV, 0x07);
	Gy521_Write_Byte(CONFIG, 0x06);
	Gy521_Write_Byte(GYRO_CONFIG, 0x18);
	Gy521_Write_Byte(ACCEL_CONFIG, 0x01);
	Gy521_Write_Byte(0x38,0X00);       //关闭所有中断
	Gy521_Write_Byte(0x6A,0X00);        //I2C主模式关闭
	//Gy521_Write_Byte(0x23,0X00);          //关闭FIFO
	//Gy521_Write_Byte(ACCEL_CONFIG,0x1C);     //加速度传感器量程和高通滤波器配置
I2C_MPU6050_WriteData(PWR_MGMT_1, 0x00);
I2C_MPU6050_WriteData(SMPLRT_DIV, 0x07);
I2C_MPU6050_WriteData(CONFIG, 0x06);
I2C_MPU6050_WriteData(GYRO_CONFIG, 0x18);
I2C_MPU6050_WriteData(ACCEL_CONFIG, 0x01);
I2C_MPU6050_WriteData(0x38,0X00);
I2C_MPU6050_WriteData(0x6A,0X00);
}
hi_s16 GetData(unsigned char REG_Address)
{
	unsigned char buf[2] = {0};
    GY521_Read_Len(GY521_ADDR,REG_Address,2,buf);

	return (buf[0]<<8)+buf[1];   //合成数据
}
void IMUupdate(float gx, float gy, float gz, float ax, float ay, float az)
{
        float norm;
        float vx, vy, vz;
        float ex, ey, ez;   
        // 测量正常化
        norm = sqrt(ax*ax + ay*ay + az*az);      
        ax = ax / norm;                   //
        ay = ay / norm;
        az = az / norm;
        // 估计方向的重力
        vx = 2*(q1*q3 - q0*q2);
        vy = 2*(q0*q1 + q2*q3);
        vz = q0*q0 - q1*q1 - q2*q2 + q3*q3; 
        // 错误的领域和方向传感器测量参考方向之间的交叉乘积的总和
        ex = (ay*vz - az*vy);
        ey = (az*vx - ax*vz);
        ez = (ax*vy - ay*vx); 
        // 积分误差比例积分增益
        exInt = exInt + ex*Ki;
        eyInt = eyInt + ey*Ki;
        ezInt = ezInt + ez*Ki; 
        // 调整后的陀螺仪测量
        gx = gx + Kp*ex + exInt;
        gy = gy + Kp*ey + eyInt;
        gz = gz + Kp*ez + ezInt; 
        // 整合四元数率和正常化
        q0 = q0 + (-q1*gx - q2*gy - q3*gz)*halfT;
        q1 = q1 + (q0*gx + q2*gz - q3*gy)*halfT;
        q2 = q2 + (q0*gy - q1*gz + q3*gx)*halfT;
        q3 = q3 + (q0*gz + q1*gy - q2*gx)*halfT;   
        // 正常化四元
        norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);
        q0 = q0 / norm;
        q1 = q1 / norm;
        q2 = q2 / norm;
        q3 = q3 / norm; 
        Pitch  = asin(-2 * q1 * q3 + 2 * q0* q2)* 57.3; // pitch ,转换为度数
        Roll = atan2(2 * q2 * q3 + 2 * q0 * q1, -2 * q1 * q1 - 2 * q2* q2 + 1)* 57.3; // rollv
        Yaw = atan2(2*(q1*q2 + q0*q3),q0*q0+q1*q1-q2*q2-q3*q3) * 57.3;   //此处没有价值，注掉
}
float AccX, AccY, AccZ;

float GyroX, GyroY, GyroZ;

hi_void *gy521_mpu6050(hi_void* param)
{float a=0;

    hi_unref_param(param);
    InitMPU6050();	//初始化MPU6050
	hi_sleep(150);
	while(1)
	{
       // AccX = GetData(ACCEL_XOUT_H)/ 16384.0;	//显示X轴加速度

        //AccY = GetData(ACCEL_YOUT_H)/ 16384.0;	//显示Y轴加速度
       // AccZ = GetData(ACCEL_ZOUT_H)/ 16384.0;	//显示Z轴加速度
      //  GyroX = GetData(GYRO_XOUT_H) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
      //  GyroY = GetData(GYRO_YOUT_H) / 131.0;
        GyroZ = GetData(GYRO_ZOUT_H) / 50;
        //IMUupdate(GyroX, GyroY, GyroZ,AccX, AccY, AccZ);
        printf("yaw : %.02f \n",GyroZ);
      
		hi_sleep(1000);
	}
}

void MPU6050ID(void)
{
	unsigned char Re = 0;
	//MPU6050_ReadData(0x75,&Re,1);  
    //GY521_Read_Len(0x75,0x68,1,&Re);  //读器件地址
    hi_i2c_read(HI_I2C_IDX_0, 0x75,&Re);
    printf("MPU%f\r\n",Re);
	if(Re != 0x68)
	{
		printf("MPU6050 dectected error!\r\n");
		return 0;
	}
	else
	{
		return 1;
	}
}

#define GY521_TASK_STACKSIZE  0x1000   
#define GY521_TASK_PRIOR 28
#define GY521_TASK_NAME "GY521DEMO"
int app_demo_gy521(void)
{
    hi_u32 ret;
    hi_task_attr attr = {0};
    hi_u32 taskID;
    attr.stack_size = GY521_TASK_STACKSIZE;
    attr.task_prio = GY521_TASK_PRIOR;
    attr.task_name = GY521_TASK_NAME;
    ret = hi_task_create(&taskID, &attr, gy521_mpu6050, NULL);
    if (ret != HI_ERR_SUCCESS) {
       printf("GY521 TASK CTREATE FAILED");
    }

    return 0;
}